from django.core import cache
from rest_framework.views import APIView
from rest_framework.response import Response
from django.shortcuts import HttpResponse
from .sers import *
from utils.make_image_code import ImageCode
import jwt
from rest_framework.generics import CreateAPIView,GenericAPIView
from rest_framework.mixins import CreateModelMixin

import redis

r = redis.Redis()


# Create your views here.

class Login(APIView):
    def post(self, request):
        ser = LoginSer(data=request.data)
        if ser.is_valid():  # 数据验证后会存放到validated_data中
            # 获取令牌
            token = ser.validated_data.get('token')
            uid = ser.validated_data.get('uid')
            return Response({'status': 200, 'msg': '登录成功', 'token': token, 'uid': uid})
        else:
            print(ser.errors)
            return Response({'status': 500, 'msg': '登录失败'})


# class Register(CreateAPIView):
#     serializers_class = UserSer
#
#     def get_serializer_class(self):
class Register(APIView):
    def post(self, request):
        ser = UserSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'status': 200, 'msg': '注册成功'})
        else:
            print(ser.errors)
            return Response({'status': 500, 'msg': '注册失败'})


def Make_Image_Code(request):
    func = ImageCode()
    # 生成验证码
    code_list = func.make_code()
    # 把验证码列表改为字符串
    code_str = ''.join(code_list)
    # 获取uuid
    uuid = request.GET.get('uuid')
    print(uuid)

    # 保存验证码字符串到cache中
    # c = cache.cache
    # c.set(uuid, code_str, 60)  # key   value   有效期（秒）
    # 保存验证码字符串到redis中
    r.set(uuid, code_str, ex=60)  # key   value   有效期（秒）
    return HttpResponse(func.make_code_image(code_list), content_type='image/png')
